package com.mmall.service.impl;

import com.mmall.service.IFileService;
import com.mmall.util.FtpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by root on 18-4-8.
 */
@Service
public class FileServiceImpl implements IFileService{
    private static Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    public String upload(MultipartFile file, String path){
        if (file == null || StringUtils.isBlank(path)){
            return null;
        }
        String fileName = file.getOriginalFilename();
        String fileExtendName = fileName.substring(fileName.lastIndexOf(".") + 1);
        String uploadFileName = UUID.randomUUID() + "." + fileExtendName;
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }
        File uploadFile = new File(path, uploadFileName);
        try {
            file.transferTo(uploadFile);
        } catch (IOException e) {
            logger.error("upload file" + fileName + " failed .", e);
        }
        //save to ftp
        if (FtpUtil.upload("img", uploadFile)){
            uploadFile.delete();
        } else {
            logger.info(fileName + " save to ftp failed");
        }

        return uploadFileName;
    }
}
